import { useState } from 'preact/hooks'
import { useWebSocket } from '../hooks/useWebSocket'

export default function ControlPanel({
  setGraphData,
  setRecommendations,
  setIsProcessing,
  setStatusMessage,
  isProcessing,
}) {
  const [postContent, setPostContent] = useState('')
  const [userId] = useState('demo_user')
  const [isExpanded, setIsExpanded] = useState(true)

  const { sendMessage, isConnected } = useWebSocket({
    onNodeAdded: (node) => {
      // 添加新节点，并标记为高亮
      const highlightedNode = { ...node, highlighted: true, new: true, val: 20 }
      setGraphData((prev) => ({
        ...prev,
        nodes: [...prev.nodes, highlightedNode],
      }))

      setStatusMessage(`💡 新话题：${node.label}`)

      // 3秒后取消高亮和new标记，恢复正常大小
      setTimeout(() => {
        setGraphData((prev) => ({
          ...prev,
          nodes: prev.nodes.map(n =>
            n.id === node.id ? { ...n, highlighted: false, new: false, val: 8 } : n
          ),
        }))
      }, 3000)
    },
    onEdgeAdded: (edge) => {
      setGraphData((prev) => ({
        ...prev,
        links: [...prev.links, edge],
      }))
    },
    onRecommendationPath: (recommendation) => {
      setRecommendations((prev) => [...prev, recommendation])
    },
    onProcessingStart: () => {
      setIsProcessing(true)
      setStatusMessage('开始分析帖子...')
    },
    onProcessingComplete: () => {
      setIsProcessing(false)
      setStatusMessage('推荐生成完成！')
      setTimeout(() => setStatusMessage(''), 3000)
    },
    onAnalysisComplete: (analysis) => {
      setStatusMessage(`识别到话题: ${analysis.topics?.join(', ')}`)
    },
  })

  const handleSubmit = (e) => {
    e.preventDefault()

    if (!postContent.trim()) {
      alert('请输入内容')
      return
    }

    if (!isConnected) {
      alert('WebSocket未连接，请刷新页面')
      return
    }

    // 清空之前的推荐
    setRecommendations([])

    // 发送消息到后端
    sendMessage({
      type: 'post',
      content: postContent,
      user_id: userId,
    })

    // 清空输入
    // setPostContent('')
  }

  const handleCounterRecommendation = () => {
    if (!isConnected) {
      alert('WebSocket未连接，请刷新页面')
      return
    }

    setRecommendations([])
    setIsProcessing(true)
    setStatusMessage('正在生成反向推荐...')

    sendMessage({
      type: 'request_counter_recommendation',
      user_id: userId,
    })
  }

  // 预设示例 - 精心设计以展示系统功能
  const examples = [
    {
      text: '我想学习深度学习和计算机视觉，需要什么数学基础？',
      emoji: '✨',
      tag: '跨域推荐'
    },
    {
      text: '正在研究大语言模型，想了解Transformer和BERT的原理',
      emoji: '🎯',
      tag: '精确匹配'
    },
    {
      text: '做推荐系统需要了解协同过滤和知识图谱吗？',
      emoji: '🔗',
      tag: '多领域链接'
    },
    {
      text: '想用Neo4j做图数据库，需要学习哪些图算法？',
      emoji: '💡',
      tag: '技术栈'
    },
    {
      text: '如何设计分布式系统？需要考虑微服务和负载均衡',
      emoji: '🚀',
      tag: '系统架构'
    }
  ]

  return (
    <div
      class={`absolute left-0 top-24 z-10 transition-all duration-300 ${
        isExpanded ? 'w-96' : 'w-12'
      }`}
    >
      {/* 展开/收起按钮 */}
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        class="absolute right-0 top-0 w-12 h-12 bg-dark/90 backdrop-blur-sm border border-primary/30 rounded-r-lg flex items-center justify-center hover:bg-primary/20 transition-colors"
      >
        <span class="text-primary text-xl">{isExpanded ? '←' : '→'}</span>
      </button>

      {isExpanded && (
        <div class="bg-dark/90 backdrop-blur-sm border-r border-primary/30 p-6 h-[calc(100vh-6rem)] overflow-y-auto fade-in">
          <h2 class="text-xl font-bold mb-4 text-primary">发布帖子</h2>

          {/* 连接状态 */}
          <div class="mb-4 flex items-center gap-2">
            <div
              class={`w-2 h-2 rounded-full ${
                isConnected ? 'bg-green-500' : 'bg-red-500'
              } ${isConnected ? 'animate-pulse' : ''}`}
            />
            <span class="text-xs text-gray-400">
              {isConnected ? '已连接' : '未连接'}
            </span>
          </div>

          {/* 输入表单 */}
          <form onSubmit={handleSubmit} class="space-y-4">
            <div>
              <label class="block text-sm text-gray-300 mb-2">内容</label>
              <textarea
                value={postContent}
                onInput={(e) => setPostContent(e.target.value)}
                placeholder="输入你的问题或想法..."
                class="w-full h-32 bg-darker border border-primary/30 rounded-lg px-3 py-2 text-white placeholder-gray-500 focus:outline-none focus:border-primary resize-none"
                disabled={isProcessing}
              />
            </div>

            <button
              type="submit"
              disabled={isProcessing || !isConnected}
              class="w-full bg-gradient-to-r from-primary to-secondary text-dark font-bold py-3 rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isProcessing ? '处理中...' : '发布并获取推荐'}
            </button>
          </form>

          {/* 示例 */}
          <div class="mt-6">
            <h3 class="text-sm font-semibold text-gray-300 mb-3">快速示例</h3>
            <div class="space-y-2">
              {examples.map((example, index) => (
                <button
                  key={index}
                  onClick={() => setPostContent(example.text)}
                  class="w-full text-left bg-darker/50 hover:bg-darker border border-gray-700 rounded-lg px-3 py-3 text-gray-300 hover:text-white transition-all hover:border-primary/30 group"
                  disabled={isProcessing}
                >
                  <div class="flex items-start gap-2">
                    <span class="text-base flex-shrink-0">{example.emoji}</span>
                    <div class="flex-1 min-w-0">
                      <div class="text-xs text-gray-300 group-hover:text-white leading-relaxed">
                        {example.text}
                      </div>
                      <div class="mt-1.5 inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary border border-primary/20">
                        {example.tag}
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* 反向推荐按钮 */}
          <div class="mt-6 pt-6 border-t border-gray-700">
            <h3 class="text-sm font-semibold text-gray-300 mb-3">高级功能</h3>
            <button
              onClick={handleCounterRecommendation}
              disabled={isProcessing || !isConnected}
              class="w-full bg-gradient-to-r from-purple-600 to-pink-600 text-white font-bold py-3 rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
            >
              打破信息茧房
            </button>
            <p class="text-xs text-gray-400 mt-2">
              获取反向推荐，发现意外但有意义的内容
            </p>
          </div>

          {/* 图例 */}
          <div class="mt-6 pt-6 border-t border-gray-700">
            <h3 class="text-sm font-semibold text-gray-300 mb-3">图例</h3>
            <div class="space-y-2 text-xs">
              <div class="flex items-center gap-2">
                <div class="w-3 h-3 rounded-full bg-[#4ECDC4]" />
                <span class="text-gray-400">话题节点</span>
              </div>
              <div class="flex items-center gap-2">
                <div class="w-3 h-3 rounded-full bg-[#FF6B6B]" />
                <span class="text-gray-400">用户节点</span>
              </div>
              <div class="flex items-center gap-2">
                <div class="w-3 h-3 rounded-full bg-[#00D9FF]" />
                <span class="text-gray-400">常规推荐</span>
              </div>
              <div class="flex items-center gap-2">
                <div class="w-3 h-3 rounded-full bg-[#FF00FF]" />
                <span class="text-gray-400">反向推荐</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
